package org.dromara.common.encrypt.config;

import jakarta.servlet.DispatcherType;
import org.dromara.common.encrypt.filter.CryptoFilter;
import org.dromara.common.encrypt.properties.ApiDecryptProperties;
import org.springframework.boot.autoconfigure.AutoConfiguration;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.boot.web.servlet.FilterRegistrationBean;
import org.springframework.context.annotation.Bean;


/**
 * @Author 刘武贵
 * @Date 2024/8/15 22:00
 * @Description 功能描述：api 解密自动配置
 */
@AutoConfiguration
// 启用ApiDecryptProperties配置属性
@EnableConfigurationProperties(ApiDecryptProperties.class)
// 当配置属性"api-decrypt.enabled"的值为"true"时，该注解使能相应的功能
@ConditionalOnProperty(value = "api-decrypt.enabled", havingValue = "true")
public class ApiDecryptAutoConfiguration {

    @Bean
    public FilterRegistrationBean<CryptoFilter> cryptoFilterRegistration(ApiDecryptProperties properties) {
        // 创建一个FilterRegistrationBean实例，用于注册CryptoFilter过滤器
        FilterRegistrationBean<CryptoFilter> registration = new FilterRegistrationBean<>();
        // 设置过滤器的请求类型为REQUEST，表示该过滤器将在请求派发之前执行
        registration.setDispatcherTypes(DispatcherType.REQUEST);
        // 设置要注册的过滤器实例为CryptoFilter，并传入配置信息
        registration.setFilter(new CryptoFilter(properties));
        // 为过滤器指定应用到所有请求路径
        registration.addUrlPatterns("/*");
        // 设置过滤器的名称为"cryptoFilter"
        registration.setName("cryptoFilter");
        // 设置过滤器的优先级为最高，确保它在其他过滤器之前执行
        registration.setOrder(FilterRegistrationBean.HIGHEST_PRECEDENCE);
        return registration;
    }
}
